﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.Security;
using SharpDiary.Core.Utility;
using SharpDiary.Core.ORMapping;
using System.IO;

namespace SharpDiary.Diary
{
    public partial class frmSignIn : Form
    {
        private readonly string USER_NAME = "UserName";
        private readonly string PASSWORD = "Password";
        private bool _isPasswordEncryped = false; //密码是否已经md5加密

        private UserInfo _currentUserInfo;
        AuthorityManager _authorityManager = new AuthorityManager();

        /// <summary>
        /// 获取用户信息。
        /// </summary>
        public UserInfo CurrentUserInfo
        {
            get { return _currentUserInfo; }
        }

        /// <summary>
        /// 获取或设置用户名称。
        /// </summary>
        public string UserName
        {
            get { return textBoxUserName.Text; }
            set
            {
                if (value != null)
                {
                    textBoxUserName.Text = value;
                }
            }
        }

        /// <summary>
        /// 获取或设置登录密码。
        /// </summary>
        public string Password
        {
            get { return textBoxPassword.Text; }
            set
            {
                if (value != null)
                {
                    textBoxPassword.Text = value;
                }
            }
        }

        public frmSignIn()
        {
            InitializeComponent();


        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            lblMemo.Text = Utils.GetRandomMemo();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            pnlBk.Enabled = false;
            Application.DoEvents();

            _authorityManager.SignInCompleted += new EventHandler<SignInCompletedEventArgs>(authorityManager_SignInCompleted);
            _authorityManager.SignInAsync(UserName, Password, _isPasswordEncryped);
        }

        /// <summary>
        /// 保存登录信息以便下次使用。
        /// </summary>
        private void RememberSignInInfo()
        {
            Properties.Settings.Default.RememberSignInInfo = chbRemeberSignInInfo.Checked;
            Properties.Settings.Default.UserName = textBoxUserName.Text;

            if (!_isPasswordEncryped)
            {
                Properties.Settings.Default.Password = MD5Helper.GenerateToMD5HexString(textBoxPassword.Text);
            }
            else
            {
                Properties.Settings.Default.Password = textBoxPassword.Text;
            }

            Properties.Settings.Default.Save();
        }

        private void authorityManager_SignInCompleted(object sender, SignInCompletedEventArgs e)
        {
            pnlBk.Enabled = true;

            _currentUserInfo = _authorityManager.CurrentUserInfo;

            if (e.Success)
            {
                //记住登录信息
                RememberSignInInfo();

                this.DialogResult = DialogResult.OK;
                Close();
            }
            else
            {
                popupMessageControl.Show(e.FailReason);

                if (textBoxUserName.Text.Length > 0)
                {
                    textBoxUserName.Focus();
                    textBoxUserName.SelectAll();
                }
                else if (textBoxPassword.Text.Length > 0)
                {
                    textBoxPassword.Focus();
                    textBoxPassword.SelectAll();
                }
            }
        }

        /// <summary>
        /// 随机显示格言。
        /// </summary>
        private void ShowRandomMemo()
        {
            lblMemo.Text = Utils.GetRandomMemo();
        }

        /// <summary>
        /// 添加格言。
        /// </summary>
        private void AppendMemo()
        {
            using (frmAppendMemo dlg = new frmAppendMemo())
            {
                dlg.ShowDialog();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Close();
        }

        private void lblMemo_Click(object sender, EventArgs e)
        {
            ShowRandomMemo();
        }

        private void miRandomMemo_Click(object sender, EventArgs e)
        {
            ShowRandomMemo();
        }

        private void miNewMemo_Click(object sender, EventArgs e)
        {
            AppendMemo();
        }

        private void miCopyToClipboard_Click(object sender, EventArgs e)
        {
            //复制当前格言内容到剪贴板
            if (lblMemo.Text.Length > 0)
            {
                Clipboard.SetText(lblMemo.Text);
            }
        }

        private void textBoxUserName_TextChanged(object sender, EventArgs e)
        {
            popupMessageControl.Hide();
            btnOk.Enabled = textBoxUserName.Text.Trim().Length > 0;
            chbRemeberSignInInfo.Enabled = textBoxUserName.Text.Trim().Length > 0;
        }

        private void textBoxPassword_TextChanged(object sender, EventArgs e)
        {
            popupMessageControl.Hide();
        }

        /// <summary>
        /// 加载记忆的用户登录信息。
        /// </summary>
        private void LoadRemeberedSignInInfo()
        {
            _isPasswordEncryped = false;

            if (Properties.Settings.Default.RememberSignInInfo)
            {
                _isPasswordEncryped = true; //上次登录被记住的密码是经 md5 加密后的密文。

                textBoxUserName.Text = Properties.Settings.Default.UserName;
                chbRemeberSignInInfo.Checked = true;

                textBoxPassword.Text = Properties.Settings.Default.Password;
                chbRemeberSignInInfo.Checked = true;

                _isPasswordEncryped = true;
            }
        }

        private void frmSignIn_Shown(object sender, EventArgs e)
        {
            LoadRemeberedSignInInfo();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.DefaultExt = ".txt";
                sfd.Filter = "class (*.cs)|*.cs";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter stream = new StreamWriter(sfd.FileName, false, Encoding.UTF8))
                    {
                        stream.Write(SharpDiary.Core.Data.DbObjectMappingHelper.GenerateEntityClassCode(
                            "select * from DiaryGroupInfo",
                            "DiaryGroupInfo",
                            System.IO.Path.GetFileNameWithoutExtension(sfd.FileName)));
                    }
                    MessageBox.Show("Ok.");
                }
            }
        }

        private void textBoxPassword_ModifiedChanged(object sender, EventArgs e)
        {
            _isPasswordEncryped = false;
        }
    }
}
